package com.pearl.db;

import com.pearl.entitys.dataBaseTable.UserRole;
import com.pearl.utils.Where;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserRoleDao {

  private final String SQL_INS = "INSERT INTO user(id,user_id,role_id) VALUES (?,?,?)";
  private final String SQL_UPD = "UPDATE user SET user_id=?,role_id=? WHERE id=?";
  private final String SQL_SEL = "SELECT id,user_id,role_id FROM user ";
  private final Connection conn;

  public UserRoleDao(Connection conn) {
    this.conn = conn;
  }

  public UserRole selectbyId(String id) throws SQLException {
    UserRole result = null;
    try (PreparedStatement ps = conn.prepareStatement(SQL_SEL + "WHERE userId = ?")) {
      ps.setString(1, id);
      ResultSet rs = ps.executeQuery();
      result = convert(rs);
      return result;
    } catch (SQLException e) {
      throw new SQLException(e.getMessage());
    }
  }

  public List<UserRole> selectAll() throws SQLException {
    ArrayList<UserRole> result = new ArrayList<UserRole>();
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_SEL)) {
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        result.add(convert(rs));
      }
      return result;
    }
  }

  public int insert(UserRole data) throws SQLException {
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_INS)) {
      ps.setString(1, data.getId());
      ps.setString(2, data.getUserId());
      ps.setString(3, data.getRoleId());
      return ps.executeUpdate();
    }
  }


  public int insert(List<UserRole> dataList) throws SQLException {
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_INS)) {
      for (UserRole data : dataList) {
        ps.setString(1, data.getId());
        ps.setString(2, data.getUserId());
        ps.setString(3, data.getRoleId());
        ps.addBatch();
      }
      return ps.executeBatch().length;
    }
  }


  public int update(UserRole data) throws SQLException {
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_UPD)) {
      ps.setString(1, data.getId());
      ps.setString(2, data.getUserId());
      ps.setString(3, data.getRoleId());
      return ps.executeUpdate();
    }
  }

  public List<UserRole> selectByWhere(Where where) throws SQLException {
    ArrayList<UserRole> result = new ArrayList<UserRole>();
    try (PreparedStatement ps = where.prepareStatement(this.conn, SQL_SEL)) {
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        result.add(convert(rs));
      }
      return result;
    }
  }

  private UserRole convert(ResultSet rs) throws SQLException {
    UserRole data = new UserRole();
    int index = 1;
    data.setId(rs.getString(index++));
    data.setUserId(rs.getString(index++));
    data.setRoleId(rs.getString(index++));
    return data;

  }
}
